#include <cstdlib>
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "Common.hpp"
#include "InetAddr.hpp"

void Usage(std::string proc) {
    std::cout << "The usage is " << proc << " + server_ip + server_port";
}
int main(int argc, char* argv[]) {
    if(argc != 3) {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    std::string _ip = argv[1];
    uint16_t _port = std::stoi(argv[2]);
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0) {
        std::cerr << "socket erro" << std::endl;
        exit(SOCKET_ERR);
    }
    InetAddr serveraddr(_ip, _port);
    int n = connect(sockfd, serveraddr.NetAddrPtr(), serveraddr.NetAddrLen());
    if(n < 0) {
        std::cerr << "connect erro" << std::endl;
        exit(CONNECT_ERR);
    }
    while(1) {
        std::string line;
        std::cout << "Please Enter# ";
        std::getline(std::cin, line);
        write(sockfd, line.c_str(), line.size()); // 读取数据
        char buffer[1024];
        ssize_t size = read(sockfd, buffer, sizeof(buffer));
        if(size > 0) {
            buffer[size] = '\0';
            std::cout << "server echo#" << buffer << std::endl;
        }
    }
    return 0;
}